package com.admin.service.impl;

import com.admin.entity.Station;
import com.admin.entity.Terminal;
import com.admin.entity.TerminalKey;
import com.admin.enums.TerminalLineType;
import com.admin.enums.TerminalLockType;
import com.admin.excelList.TerminalList;
import com.admin.mapper.OnandofflinetimeMapper;
import com.admin.mapper.StationMapper;
import com.admin.mapper.TerminalKeyMapper;
import com.admin.mapper.TerminalMapper;
import com.admin.requestBody.TerminalPasswordRequest2;
import com.admin.service.ITerminalService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  终端业务实现类
 * </p>
 *
 * @author marisheng
 * @since 2019-11-15
 */
@SuppressWarnings("ALL")
@Service
public class TerminalServiceImpl extends ServiceImpl<TerminalMapper, Terminal> implements ITerminalService {

    @Autowired
    private  TerminalMapper terminalMapper;

    @Autowired
    private TerminalKeyMapper terminalKeyMapper;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private OnandofflinetimeMapper onandofflinetimeMapper;

    @Autowired
    @Qualifier("StringRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private OnandofflinetimeServiceImpl onandofflinetimeService;
    /**
     * 终端查询所有
     * @param map
     * @return
     */
    @Override
    public IPage selectTerminal(int page, int limit, Map map) {
        Page p=new Page(page,limit);
        IPage iPage = terminalMapper.selectTerminal(p, map);
        return iPage;
    }

    /**
     * 判断终端统计的站点Id是否存在
     * @param stationId
     * @return
     */
    @Override
    public boolean findByStationId(String stationId){
        if (stationId != null) {
            QueryWrapper q=new QueryWrapper();
            q.eq("terminal_Station",stationId);
            int station = terminalMapper.selectCount(q);
            if (station ==0) {
                return false;
            }
        }
        return true;
    }

    /**
     *  查询终端的上下线历史记录
     * @param map   开始时间 和 结束时间
     * @return
     */
    @Override
    public IPage queryStatrtAndEndTime(int page,int limit,Map map) {

        Date onlinetime = (Date) map.get("onlinetime");
        Date offlinetime = (Date) map.get("offlinetime");

        Page page1=new Page(page,limit);

        IPage iPage = terminalMapper.queryStatrtAndEndTime(page1, map);

        return iPage;
    }

    /**
     * 解锁
     * @param terminalLock
     * @param terminalId
     * @return
     */
    @Override
    public int updateLockById(String terminalLock, Integer terminalId) {
        //terminalLock是表格中当前列中的状态
        if(terminalLock.equals("正常")){
            terminalLock="已锁定";
        }else{
            terminalLock="审核中";

            //调用修改终端审核
            updateTShenhe(terminalId);
        }
         int n = terminalMapper.updateLockById(terminalLock, terminalId);
        return n;
    }

    /**
     * 终端列表查询所有或模糊查 房间号 /mac/ ip地址
     * @param page
     * @param limit
     * @param m
     * @return
     */
    @Override
    public IPage queryIpMacFjAll(int page, int limit, Map m) {
        Page p = new Page(page, limit);
        IPage result = terminalMapper.queryIpMacFjAll(p, m);
        return result;
    }

    /**
     * 导出excel
     * @param page
     * @param limit
     * @param m
     * @return
     */
    @Override
    public IPage excelTerminal(int page, int limit, Map m) {

        Page p = new Page(page, limit);

        IPage result = terminalMapper.excelTerminal(p, m);

        return result;
    }

    /**
     * 密钥列表
     * @param page
     * @param limit
     * @param m
     * @return
     */
    @Override
    public IPage queryTerminalKeyS(int page,int limit,Map m) {

        Page page1=new Page(page,limit);

        IPage iPage = terminalMapper.queryTerminalKey(page1, m);

        return iPage;
    }

    /**
     * 终端统计
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @Override
    public IPage querysystemStatistics(int page,int limit,Map map){
        Page p=new Page(page,limit);
        IPage result=terminalMapper.querysystemStatistics(p,map);
        return result;
    }

    /**
     * 根据mac地址查找所属终端
     * @param mac
     * @return 终端对象
     */
    @Override
    public Terminal  getTerminalByMac(String mac)
    {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("terminalMac",mac);
        Terminal t  = terminalMapper.selectOne(queryWrapper);
        return t;
    }

    /**
     * 分组列表 操作查看每个分组的所有终端
     * @param page 页
     * @param limit 条数据
     * @param map 查询参数
     * @return
     */
    @Override
    public IPage groupQueryTerminal(int page, int limit, Map map){
        Page page1=new Page(page,limit);

        IPage iPage = terminalMapper.groupQueryTerminal(page1, map);
        return iPage;

    }

    /**
     * 站点管理 终端列表 解绑
     * @param terminalId
     * @return
     */
    @Override
    public int updateUntyingTerminal(Integer terminalId){
        int n = terminalMapper.updateUntyingTerminal(terminalId);
        return n;
    }

    /**
     * 设置钟点房密钥授权以及标准房密钥授权
     * @param terminal
     * @param terminalKey
     * @param tp  页面传过来的参数
     * @return
     */
    @Override
    public int TerminalByIdUpdateTermainal_keyByIdupdate(Terminal terminal, TerminalKey terminalKey, TerminalPasswordRequest2 tp){
            //得到当前时间
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime time = LocalDateTime.now();
            String localTime = df.format(time);
            LocalDateTime ldt = LocalDateTime.parse(localTime, df);

            terminalKey.setTerminalKeyBeginTime(ldt); //设置密钥的开始
            terminalKey.setTerminalKeyStatus("使用中");//设置密钥的状态
            terminalKey.setTerminalKey(terminal.getTerminalId());

            Long second = time.toEpochSecond(ZoneOffset.of("+8"));

            terminal.setTerminal_key(terminalKey.getTerminalKeyValue());
            terminal.setTerminal_key_id(terminalKey.getTerminalKeyId());
            terminal.setTerminalLine(TerminalLineType.在线.name());
            terminal.setTerminalLock(TerminalLockType.正常.name());
            Station station = stationMapper.selectById(terminal.getTerminalStation());//查询站点
            if(tp.getTerminalKeyEndTime()==null) {
            //设置标准房的结束时间
            LocalDateTime changeTime = time.plusDays(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = changeTime.format(formatter);
            LocalDateTime ldd = LocalDateTime.parse(format, formatter);

            //把明天时间转成明天de秒数
             Long mtmiaoshui = ldd.toEpochSecond(ZoneOffset.of("+8"));
             long cha=mtmiaoshui-second;
             long z=cha/60;
             if(terminal.getTerminalTotalOnlineTime()==null){
                 terminal.setTerminalTotalOnlineTime(0l);
             }
             terminal.setTerminalTotalOnlineTime(terminal.getTerminalTotalOnlineTime()+z);
            //存redis
            redisTemplate.boundValueOps("miyaoKey_" + terminalKey.getTerminalKeyId()).set("0",z, TimeUnit.MINUTES);
            terminalKey.setTerminalKeyEndTime(ldd);//结束时间
            terminalKey.setTerminalRoomType("标准房");
            terminalKeyMapper.updateById(terminalKey);

              terminalMapper.updateById(terminal);
                if(station.getStationKeyYue()>0) {
                    if(station.getStationKeyYue()==null){
                        station.setStationKeyYue(0);
                    }
                    station.setStationKeyYue(station.getStationKeyYue() - 1);
                }else {
                    return 403;
                }
                if(station.getStationAllLivingRoom()==null){
                    station.setStationAllLivingRoom(0);
                }
                station.setStationAllLivingRoom(station.getStationAllLivingRoom() + 1);
                stationMapper.updateById(station);

                return 1;
        }else {
                //获取页面传过来的日期转成毫秒数s
                Long mtmiaoshui = tp.getTerminalKeyEndTime().toEpochSecond(ZoneOffset.of("+8"));
                long ww=mtmiaoshui-second;
                long zz=ww/60;
                if(terminal.getTerminalTotalOnlineTime()==null){
                    terminal.setTerminalTotalOnlineTime(0l);
                }
                terminal.setTerminalTotalOnlineTime(terminal.getTerminalTotalOnlineTime()+zz);

                //存redis
                redisTemplate.boundValueOps("miyaoKey_" + terminalKey.getTerminalKeyId()).set("1",zz, TimeUnit.MINUTES);
                terminalKey.setTerminalKeyEndTime(tp.getTerminalKeyEndTime());
                terminalKey.setTerminalRoomType("钟点房");
                terminalKeyMapper.updateById(terminalKey);
                terminalMapper.updateById(terminal);
                if(station.getStationKeyYue()>0){
                    if(station.getStationKeyYue()==null){
                        station.setStationKeyYue(0);
                    }
                    station.setStationKeyYue(station.getStationKeyYue() - 1);
                }else {
                    return 403;
                }
                if(station.getStationHourRoom()==null){
                    station.setStationHourRoom(0);
                }
                station.setStationHourRoom(station.getStationHourRoom() + 1);
                stationMapper.updateById(station);


            }
            return 1;
    }

    /**
     * 下线所有终端:lgh
     */
    @Override
    public void offlineAllTerminal() {
        Terminal t = new Terminal();
        t.setTerminalLine("离线");
        terminalMapper.update(t,null);
    }

    @Override
    public IPage queryJieChu(int page, int limit,String tiaojian) {
        Page p = new Page(page,limit);
        IPage result = terminalMapper.queryJieChu(p,tiaojian);
        return result;
    }

    @Override
    public void updateTShenhe(int id) {
        terminalMapper.updateTShenhe(id);
    }

    @Override
    public List<TerminalList> excelTerminalList() {
        return terminalMapper.excelTerminalList();
    }

    @Override
    public int selectAdminIdByStationBh(String stationBh) {
        int updateId= stationMapper.selectIdByStationBh(stationBh);
        return updateId;
    }

    /**
     * 终端未审核的数量
     * @return
     */
    @Override
    public int terminalWeishenheCount(){
        QueryWrapper q=new QueryWrapper();
        q.eq("terminal_shenhe","未审核");
        int count=terminalMapper.selectCount(q);
        return count;
    }

}
